package at.codebase.web.servlets.item;

import static at.codebase.web.util.i18n.I18NFactory.i18n;

import java.util.ArrayList;
import java.util.Map;

import at.codebase.core.LinkCreator;
import at.codebase.db.dao.EImageDao;
import at.codebase.db.dao.EItemDao;
import at.codebase.db.entities.EImage;
import at.codebase.db.entities.EItem;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterException;
import at.codebase.web.util.servlet.SecureServlet;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.googlecode.objectify.Key;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 *
 */
public class ItemUpload extends SecureServlet {
	
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	@Override
	protected RequestType requestType() {
		return RequestType.POST_AND_GET;
	}

	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ADMIN);
		secLevels.add(UserLevel.REGISTERED);
	}

	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		try {
			long itemId = requestInfo.getParameters().getLong("itemId");
			EItem item = EItemDao.getItemById(new Long(itemId));

			if (item != null) {
				MainTemplate mainTemplate = new MainTemplate(requestInfo,writer());
				mainTemplate.setTitle(i18n(requestInfo.getLocale()).string("itemUpload_title"));
				mainTemplate.addJSScript("script_item_upload.js");
				
				Template uploadTemplate = TemplateEngine.getTemplate("item/site_upload_item.html");
				uploadTemplate.setHTML("itemLink", LinkCreator.itemLink(item.getId(), item.getTitle()));
				
				ArrayList<Template> tableRows = new ArrayList<Template>();
				 
				ArrayList<Long> ids = new ArrayList<Long>();
				for(Key<EImage> imageKey:item.getImageKeys()){
					ids.add(new Long(imageKey.getId()));
				}
				Map<Long, EImage> imageMap = EImageDao.getImagesByIds(ids);
				EImage[] images = imageMap.values().toArray(new EImage[imageMap.size()]);
				
				ArrayList<EImage> validImages = new ArrayList<EImage>();
				for(int i = 0; i < images.length; i++){
					if(images[i].getUploader().getId() == requestInfo.getUser().getId().longValue()){
						validImages.add(images[i]);
					}else if(item.checkSeller(requestInfo.getUser().getId())){
						validImages.add(images[i]);
					}else if(level.equals(UserLevel.ADMIN)){
						validImages.add(images[i]);
					}else{
						System.out.println("nothing..");
					}
				}
				
				double imagesTotal = validImages.size();
				int pointer = 0;

				for(int i = 0; i < (Math.ceil(imagesTotal/4.0d)); i++){
					Template rowTemplate = TemplateEngine.getTemplate("item/upload/image_thumbnail_list_row.html");
					for(int y = 0; y < 4; y++){
						if(pointer < imagesTotal){
							Template imageThumbnailContainer = TemplateEngine.getTemplate("item/upload/image_thumbnail_container.html");
							imageThumbnailContainer.setText("imageId", String.valueOf(validImages.get(pointer).getId()));
							imageThumbnailContainer.setText("imageUrl", "/service/image?id="+validImages.get(pointer).getId()+"&w=195&h=195");
							rowTemplate.setTemplate("image"+(y+1), imageThumbnailContainer);
							pointer++;
						}
						
					}
					tableRows.add(rowTemplate);
				}
				
				if(level.equals(UserLevel.ADMIN)){
					uploadTemplate.setHTML("removeInfo", i18n(requestInfo.getLocale()).string("itemUpload_clickToRemoveInfoAdmin"));	
				}else if(item.checkSeller(requestInfo.getUser().getId())){
					uploadTemplate.setHTML("removeInfo", i18n(requestInfo.getLocale()).string("itemUpload_clickToRemoveInfoSeller"));	
				}else{
					uploadTemplate.setHTML("removeInfo", i18n(requestInfo.getLocale()).string("itemUpload_clickToRemoveInfoCustomer"));	
				}
				
				
				uploadTemplate.setText("itemId", item.toString());
				uploadTemplate.setTemplates("imageRows", tableRows);
				uploadTemplate.setText("uploadUrl", blobstoreService.createUploadUrl("/item/itemUploadHandler?itemId="+itemId));
				
				mainTemplate.setTemplate("body", uploadTemplate);
				mainTemplate.render(requestInfo.getLocale());
			}
		} catch (ParameterException e) {
			// TODO: Wrong parameter.. Maybe Log this
		}
	}
	
	@Override
	protected void processRequestNoAccess(RequestInformation requestInfo,	UserLevel level) {
		System.out.println("No Access");
	}

}
